package com.example.apidemo2;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ivsign.android.IDCReader.IDCReadInterface;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class IDCardActivity extends Activity implements OnClickListener{
	
    private Button btnOpenIDCard;
    private Button btnReadIDCard;
    private Button btnCloseIDCard;
	private Button getBtnReadIDCardMore;
	private EditText edTimes;

    private TextView txtIDCard,tvTimesCount;
    private ImageView mImagerView;

    private int times,mSuccessTimes,mFailTimes;
    private static final String TAG = "IDCardActivity";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_idcard);
		
		initView();
	}

	private void initView() {
		// TODO Auto-generated method stub
		
        btnOpenIDCard = (Button) findViewById(R.id.btn_openIDCard);
        btnOpenIDCard.setOnClickListener(this);
        btnReadIDCard = (Button) findViewById(R.id.btn_readIDCard);
        btnReadIDCard.setOnClickListener(this);
        btnCloseIDCard = (Button) findViewById(R.id.btn_closeIDCard);
        btnCloseIDCard.setOnClickListener(this);

     //   imageIDCard = (ImageView) findViewById(R.id.idcardimage1);
        txtIDCard = (TextView) findViewById(R.id.textViewIDCard);
        mImagerView = (ImageView) findViewById(R.id.ivAvatar);

        getBtnReadIDCardMore = (Button) findViewById(R.id.btn_readIDCard_times);
        getBtnReadIDCardMore.setOnClickListener(this);

        edTimes = (EditText) findViewById(R.id.edit_times_set);
        tvTimesCount = (TextView) findViewById(R.id.tv_times_count);
	}

	@Override
	public void onClick(View v) {
		txtIDCard.setText("");
		mImagerView.setImageBitmap(null);
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_openIDCard:
			IDCReadInterface.DLL_IDOpen();
			break;
		case R.id.btn_closeIDCard:

			IDCReadInterface.DLL_IDClose();
			break;
		case R.id.btn_readIDCard:
			readIDcard(null);
			break;
		case R.id.btn_readIDCard_times:
			String timesStr = edTimes.getText().toString();
			times = Integer.parseInt(timesStr);
			Log.e(TAG,"次数是：" + times);
			readIdCardMore();
			break;
		default:
			break;
		}
		
	}

	public static final int READ_START = 1;
	public static final int SHOW_MESSAGE = 2;
	public static final int SHOW_IMAGE = 3;
	public static final int READ_ERROR = 4;

	public Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what){
				case READ_START:
					txtIDCard.setText("");
					mImagerView.setImageBitmap(null);
					break;
				case SHOW_MESSAGE:
					txtIDCard.setText(mText);
					tvTimesCount.setText("成功：" + mSuccessTimes + "次，" + "失败:" + mFailTimes);
					break;
				case SHOW_IMAGE:
					mSuccessTimes ++ ;
					mImagerView.setImageBitmap(bitmap);
					break;
				case READ_ERROR:
					mFailTimes ++;
					Toast.makeText(IDCardActivity.this, "读取失败", Toast.LENGTH_SHORT).show();
					tvTimesCount.setText("成功：" + mSuccessTimes + "次，" + "失败:" + mFailTimes);
					break;
			}

		}
	};
	public void readIdCardMore(){

		mSuccessTimes = 0;
		mFailTimes = 0;
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0; i< times; i++){
					IDCReadInterface.DLL_IDClose();
					Log.e(TAG,"DLL_IDClose");
					int ret = IDCReadInterface.DLL_IDOpen();
					Log.e(TAG,"DLL_IDOpen");
					mHandler.sendEmptyMessage(READ_START);
					if (ret != 0){
						Toast.makeText(IDCardActivity.this,"上电失败",Toast.LENGTH_SHORT);
					}
					readIDcard(new IReadCallback() {
						@Override
						public void onSuccess() {

							IDCReadInterface.DLL_IDClose();
							Log.e(TAG,"onSuccess");

						}

						@Override
						public void onFail() {
							IDCReadInterface.DLL_IDClose();
							Log.e(TAG,"onFail");
						}
					});
				}


			}
		}).start();

	}

	public interface IReadCallback{
		void onSuccess();
		void onFail();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		IDCReadInterface.DLL_IDClose();
		super.onDestroy();
	}
	private Bitmap bitmap = null;
	private String mText = "";
	 private void readIDcard(IReadCallback callback) {

		// TODO Auto-generated method stub
		   Bitmap[] bmp = new Bitmap[1];
           byte[] data = IDCReadInterface.DLL_IDReadCard(bmp);
           if(data!=null){
           		bitmap = bmp[0];
           		mHandler.sendEmptyMessage(SHOW_IMAGE);
//        	   mImagerView.setImageBitmap(bmp[0]);
           }
           if(data == null){

        	   mHandler.sendEmptyMessage(READ_ERROR);
				if(callback != null){
					callback.onFail();
				}
        	   return;
           }
           try {
               byte[] dataBuf = new byte[256];

               for(int i = 0; i < 256; i++)
               {
                   dataBuf[i] = data[6 + i];
               }

               String TmpStr = new String(dataBuf, "UTF-16LE");
               TmpStr = new String(TmpStr.getBytes("UTF-8"));

               String[] decodeInfo = new String[12];
               if(TmpStr.substring(124, 125).equals("I")) {
            	   decodeInfo[0] = TmpStr.substring(0, 60)+TmpStr.substring(79, 94); //name
                   decodeInfo[1] = TmpStr.substring(60, 61);// gender(1)
                   decodeInfo[2] = TmpStr.substring(76, 79); // nation (2)
                   decodeInfo[3] = TmpStr.substring(110, 118); // birthday (8)
                   decodeInfo[4] = ""; // address
                   decodeInfo[5] = TmpStr.substring(61, 76); //id (18)
                   decodeInfo[6] = TmpStr.substring(120, 124); //depart (15)
                   decodeInfo[7] = TmpStr.substring(94, 102); // tsYYMMDD
                   decodeInfo[8] = TmpStr.substring(102, 110); //tpYYMMDD

                   decodeInfo[10] = TmpStr.substring(118, 120);
                   decodeInfo[11] = TmpStr.substring(124, 125);


	               if (decodeInfo[1].equals("1"))
	                   decodeInfo[1] = "男";
	               else
	                   decodeInfo[1] = "女";
               }
               else {
	               decodeInfo[0] = TmpStr.substring(0, 15); //name
	               decodeInfo[1] = TmpStr.substring(15, 16); // gender(1)
	               decodeInfo[2] = TmpStr.substring(16, 18); // nation (2)
	               decodeInfo[3] = TmpStr.substring(18, 26); // birthday (8)
	               decodeInfo[4] = TmpStr.substring(26, 61); // address
	               decodeInfo[5] = TmpStr.substring(61, 79); //id (18)
	               decodeInfo[6] = TmpStr.substring(79, 94); //depart (15)
	               decodeInfo[7] = TmpStr.substring(94, 102); // tsYYMMDD
	               decodeInfo[8] = TmpStr.substring(102, 110); //tpYYMMDD
				   decodeInfo[9] =TmpStr.substring(110, 119);
				   decodeInfo[10] = TmpStr.substring(119, 121);
				   decodeInfo[11] = TmpStr.substring(124, 125);


	               if (decodeInfo[1].equals("1"))
	                   decodeInfo[1] = "男";
	               else
	                   decodeInfo[1] = "女";

	               if(!decodeInfo[2].equals("  ")) {
		               int code = Integer.parseInt(decodeInfo[2].toString());
		               decodeInfo[2] = decodeNation(code);
	               }
               }
               mText = "姓名:"+ decodeInfo[0] + "姓别：" + decodeInfo[1] +   (!decodeInfo[2].equals("  ")?" 民族："+ decodeInfo[2]:"")  + " 出生日期：" + decodeInfo[3].substring(0,4)
					   + getResources().getString(R.string.id_titleyear)
					   + "  "
					   + decodeInfo[3].substring(4,6)
					   + getResources().getString(R.string.id_titlemonth)
					   + "  "
					   + decodeInfo[3].substring(6,8)
					   + getResources().getString(R.string.id_titleday) + " 住址："+ decodeInfo[4] + " 身份证号" + decodeInfo[5]
					   + "签发机关：" + decodeInfo[6] + "签发日期：" + decodeInfo[7]+ "失效日期：" + decodeInfo[8]+" ";
//               txtIDCard.setText("姓名:"+ decodeInfo[0] + "姓别：" + decodeInfo[1] +   (!decodeInfo[2].equals("  ")?" 民族："+ decodeInfo[2]:"")  + " 出生日期：" + decodeInfo[3].substring(0,4)
//                       + getResources().getString(R.string.id_titleyear)
//                       + "  "
//                       + decodeInfo[3].substring(4,6)
//                       + getResources().getString(R.string.id_titlemonth)
//                       + "  "
//                       + decodeInfo[3].substring(6,8)
//                       + getResources().getString(R.string.id_titleday) + " 住址："+ decodeInfo[4] + " 身份证号" + decodeInfo[5]
//                       + "签发机关：" + decodeInfo[6] + "签发日期：" + decodeInfo[7]+ "失效日期：" + decodeInfo[8]+" ");// + (!decodeInfo[9].equals("         ")?" 通行证号码"+ decodeInfo[9]:"") + (!decodeInfo[10].equals("  ")?(!decodeInfo[11].equals("I")?" 签发次数:":"证件版本号:") + decodeInfo[10]:"") + (!decodeInfo[11].equals(" ")?" 卡型标识::" + decodeInfo[11]:""));
//               if(decodeInfo[9]!=null) txtIDCard.append((!decodeInfo[9].equals("         ")?"通行证号码："+ decodeInfo[9]:""));
//               if(decodeInfo[10]!=null) txtIDCard.append(!decodeInfo[10].equals("  ")?(!decodeInfo[11].equals("I")?" 签发次数:":"证件版本号:") + decodeInfo[10]:"");
//               if(decodeInfo[11]!=null) txtIDCard.append(!decodeInfo[11].equals(" ")?"卡型标识:" + decodeInfo[11]:"");
			   mHandler.sendEmptyMessage(SHOW_MESSAGE);

			   if(callback != null){
				   callback.onSuccess();
			   }
           } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
           }
	}

	private String decodeNation(int code)
	    {
	        String nation;
	        if(mList == null) {
	            //DisplayError("Not found nation code");
	            return "";
	        }

	        Log.d("idreader","code "+code);

	        if(code >= 1 && code <= 56)
	        {
	            nation = mList.get(code);
	        }else if(code == 97) {
	            nation = getResources().getString(R.string.case_97_nation);
	        }else if(code == 98){
	            nation = getResources().getString(R.string.case_98_nation);
	        }else {
	            nation = mList.get(0);
	            nation=" ";
	        }

	        Log.d("idreader","nation "+ nation);
	        return nation;
	    }
     public List<String> mList =null ;
	 public void init_date(){
	        mList= new ArrayList<String>();

	        mList.add(0,"");
	        mList.add(1, getResources().getString(R.string.case_1_nation));
	        mList.add(2, getResources().getString(R.string.case_2_nation));
	        mList.add(3, getResources().getString(R.string.case_3_nation));
	        mList.add(4, getResources().getString(R.string.case_4_nation));
	        mList.add(5, getResources().getString(R.string.case_5_nation));
	        mList.add(6, getResources().getString(R.string.case_6_nation));
	        mList.add(7, getResources().getString(R.string.case_7_nation));
	        mList.add(8, getResources().getString(R.string.case_8_nation));
	        mList.add(9, getResources().getString(R.string.case_9_nation));
	        mList.add(10, getResources().getString(R.string.case_10_nation));
	        mList.add(11, getResources().getString(R.string.case_11_nation));
	        mList.add(12, getResources().getString(R.string.case_12_nation));
	        mList.add(13, getResources().getString(R.string.case_12_nation));
	        mList.add(14, getResources().getString(R.string.case_14_nation));
	        mList.add(15, getResources().getString(R.string.case_15_nation));
	        mList.add(16, getResources().getString(R.string.case_16_nation));
	        mList.add(17, getResources().getString(R.string.case_17_nation));
	        mList.add(18, getResources().getString(R.string.case_18_nation));
	        mList.add(19, getResources().getString(R.string.case_19_nation));
	        mList.add(20, getResources().getString(R.string.case_20_nation));
	        mList.add(21, getResources().getString(R.string.case_21_nation));
	        mList.add(22, getResources().getString(R.string.case_22_nation));
	        mList.add(23, getResources().getString(R.string.case_23_nation));
	        mList.add(24, getResources().getString(R.string.case_24_nation));
	        mList.add(25, getResources().getString(R.string.case_25_nation));
	        mList.add(26, getResources().getString(R.string.case_26_nation));
	        mList.add(27, getResources().getString(R.string.case_27_nation));
	        mList.add(28, getResources().getString(R.string.case_28_nation));
	        mList.add(29, getResources().getString(R.string.case_29_nation));
	        mList.add(30, getResources().getString(R.string.case_30_nation));
	        mList.add(31, getResources().getString(R.string.case_31_nation));
	        mList.add(32, getResources().getString(R.string.case_32_nation));
	        mList.add(33, getResources().getString(R.string.case_33_nation));
	        mList.add(34, getResources().getString(R.string.case_34_nation));
	        mList.add(35, getResources().getString(R.string.case_35_nation));
	        mList.add(36, getResources().getString(R.string.case_36_nation));
	        mList.add(37, getResources().getString(R.string.case_37_nation));
	        mList.add(38, getResources().getString(R.string.case_38_nation));
	        mList.add(39, getResources().getString(R.string.case_39_nation));
	        mList.add(40, getResources().getString(R.string.case_40_nation));
	        mList.add(41, getResources().getString(R.string.case_41_nation));
	        mList.add(42, getResources().getString(R.string.case_42_nation));
	        mList.add(43, getResources().getString(R.string.case_43_nation));
	        mList.add(44, getResources().getString(R.string.case_44_nation));
	        mList.add(45, getResources().getString(R.string.case_43_nation));
	        mList.add(46, getResources().getString(R.string.case_46_nation));
	        mList.add(47, getResources().getString(R.string.case_47_nation));
	        mList.add(48, getResources().getString(R.string.case_48_nation));
	        mList.add(49, getResources().getString(R.string.case_49_nation));
	        mList.add(50, getResources().getString(R.string.case_50_nation));
	        mList.add(51, getResources().getString(R.string.case_51_nation));
	        mList.add(52, getResources().getString(R.string.case_52_nation));
	        mList.add(53, getResources().getString(R.string.case_53_nation));
	        mList.add(54, getResources().getString(R.string.case_54_nation));
	        mList.add(55, getResources().getString(R.string.case_55_nation));
	        mList.add(56, getResources().getString(R.string.case_56_nation));
	    }

}
